<?php

ini_set('max_execution_time', '3600');
ini_set('memory_limit', '512M');

/**
 * Migrációs osztály.
 *
 * @author poli
 */
class MigrationHandler {

	private static function initMigrDb() {
		global $MIGR_DB_CONNECTIONINFO, $MIGR_DB_OPTIONS;

		// regisztráció
		DBHandler::registerHandler('migrationdb', $MIGR_DB_CONNECTIONINFO, $MIGR_DB_OPTIONS);
	}

	/**
	 * A cikkeket és menüket migrálja.
	 *
	 * @param bool $isTruncate Kell-e törölni a táblát előbb?
	 */
	public static function migrateArticles() {
		MigrationHandler::initMigrDb();
		$db = DBHandler::dbGetDBHandler();
		$migrDb = DBHandler::dbGetDBHandler('migrationdb');
		try {
			$db->beginTransaction();
			$nullFilter = new DBQueryFilter();
			$menus =& GeneralDBHelper::getTableRowsFilteredInTransaction($migrDb->get(), 'menu_fix', $nullFilter);
			if (PEAR::isError($menus)) {
				throw new Exception($menus->getDebugInfo());
			} else {
				foreach ($menus as $menu) {
					if (! empty($menu['szoveg'])) {
						// menü cikk felvitele
						$articleId = AdminDBHelper::addArticle(SiteHandler::getCurrentSiteId(), null, $menu['langcode'], ARTICLE_TYPE_NORMAL);

						$data = array(
							'id' => $articleId,
							'langcode' => $menu['langcode'],
							'site_id' => SiteHandler::getCurrentSiteId(),
							'worktitle' => $menu['cim'],
							'title' => $menu['cim'],
							'body' => $menu['szoveg']
						);
						AdminDBHelper::modArticle($data);

						// a menü maga
						$data = array(
							'parentid' => -1,
							'langcode' => $menu['langcode'],
							'menu_group_id' => 100,
							'label' => $menu['cim'],
							'article_id' => $articleId,
							'target_type' => MENU_TARGETTYPE_ARTICLE,
						);
						$menuId = GeneralDBHelper::addTableRowInTransaction($db->get(), 'menu', $data);

						// almenük
						$filter = new DBQueryFilter();
						$filter->addComponent('menu_fix_id', DBQueryFilter::OP_EQUALS, $menu['id']);
						$subMenus =& GeneralDBHelper::getTableRowsFilteredInTransaction($migrDb->get(), 'menu_al', $filter);
						foreach ($subMenus as $subMenu) {
							if (! empty($subMenu['szoveg'])) {
								// menü cikk felvitele
								$articleId = AdminDBHelper::addArticle(SiteHandler::getCurrentSiteId(), null, $menu['langcode'], ARTICLE_TYPE_NORMAL);

								$data = array(
									'id' => $articleId,
									'langcode' => $menu['langcode'],
									'site_id' => SiteHandler::getCurrentSiteId(),
									'worktitle' => $subMenu['cim'],
									'title' => $subMenu['cim'],
									'body' => $subMenu['szoveg']
								);
								AdminDBHelper::modArticle($data);

								// az almenü maga
								$data = array(
									'parentid' => $menuId,
									'langcode' => $menu['langcode'],
									'menu_group_id' => 100,
									'label' => $subMenu['cim'],
									'article_id' => $articleId,
									'target_type' => MENU_TARGETTYPE_ARTICLE,
								);
								$subMenuId = GeneralDBHelper::addTableRowInTransaction($db->get(), 'menu', $data);
							}	
						}
					}
				}
			}
			$db->endTransaction();
			TreeStore::getInstance()->removeAllTreeObjects();
		} catch (Exception $e) {
			Log::error("Migrating articles and menus failed. Reason: ".$e->getMessage());
			try {
				$db->rollback();
				$db->endTransaction();
			} catch (Exception $e) {
				Log::error("Also, failed to rollback. Reason: ".$e->getMessage());
			}
			throw $e;
		}
	}

	/**
	 * A cikkeket és menüket migrálja.
	 *
	 * @param bool $isTruncate Kell-e törölni a táblát előbb?
	 */
	public static function migrateTournaments() {
		MigrationHandler::initMigrDb();
		$db = DBHandler::dbGetDBHandler();
		$migrDb = DBHandler::dbGetDBHandler('migrationdb');
		try {
			$db->beginTransaction();
			// verseny formák
			$nullFilter = new DBQueryFilter();
			$query = "select v.id, t.langcode, t.nev, t.megjegyzes from versenyforma v left join versenyforma_texts t on (v.id = t.id_versenyforma) order by v.id";
			$tournamentTypes =& GeneralDBHelper::runSelectQueryStringInTransactionUsingFilter($migrDb->get(), $query, array(), $nullFilter);
			$prevId = -1;
			$tournamentTypeIndex = array();
			foreach ($tournamentTypes as $tournamentType) {
				if ($prevId != $tournamentType['id']) {
					$newId = DBUtil::getSeqValue('objectid', $db->get());
					$tournamentTypeIndex[$tournamentType['id']] = $newId;
					$prevId = $tournamentType['id'];
				}
				$data = array(
					'id' => $newId,
					'langcode' => $tournamentType['langcode'],
					'name' => $tournamentType['nev'],
					'comment' => $tournamentType['megjegyzes']
				);
				GeneralDBHelper::addTableRowInTransaction($db->get(), 'tournamenttype', $data, true);
			}
			// tournaments
			$tournaments =& GeneralDBHelper::getTableRowsFilteredInTransaction($migrDb->get(), 'verseny');
			foreach ($tournaments as $tournament) {
				// alapadatok mentése
				$data = array(
					'date_from' => DBUtil::getDBFormattedTimestamp($tournament['idopont_tol']),
					'date_to' => DBUtil::getDBFormattedTimestamp($tournament['idopont_ig']),
					'deadline' => DBUtil::getDBFormattedTimestamp($tournament['idopont_tol']),
					'email' => $tournament['email_addr'],
				);
				$tournamentId = GeneralDBHelper::addTableRowInTransaction($db->get(), 'tournament', $data);

				// verseny-versenyforma kapcsolat mentés
				$filter = new DBQueryFilter();
				$filter->addComponent('id_verseny', DBQueryFilter::OP_EQUALS, $tournament['id']);
				$tournamentTypes =& GeneralDBHelper::getTableRowsFilteredInTransaction($migrDb->get(), 'verseny_versenyforma', $filter);
				foreach ($tournamentTypes as $tournamentType) {
					$data = array(
						'id_tournament' => $tournamentId,
						'id_tournamenttype' => $tournamentTypeIndex[$tournamentType['id_versenyforma']]
					);
					GeneralDBHelper::addTableRowInTransaction($db->get(), 'tournament_ttype', $data, true);
				}

				// nyelvesített tartalmak
				$filter = new DBQueryFilter();
				$filter->addComponent('id_verseny', DBQueryFilter::OP_EQUALS, $tournament['id']);
				$tournamentLangs =& GeneralDBHelper::getTableRowsFilteredInTransaction($migrDb->get(), 'verseny_texts', $filter);
				$articleIds = array();
				foreach ($tournamentLangs as $tournamentLang) {
					$data = array(
						'id_tournament' => $tournamentId,
						'langcode' => $tournamentLang['langcode'],
						'name' => $tournamentLang['nev'],
						'location' => $tournament['helyszin']
					);
					GeneralDBHelper::addTableRowInTransaction($db->get(), 'tournament_texts', $data);

					// cikkek
					// beharangozo
					if (! empty($tournamentLang['leiras'])) {
						if (isset($articleIds['intro'])) {
							AdminDBHelper::addArticle(SiteHandler::getCurrentSiteId(), $articleIds['intro'], $tournamentLang['langcode'], ARTICLE_TYPE_NORMAL);
						} else {
							$articleIds['intro'] = AdminDBHelper::addArticle(SiteHandler::getCurrentSiteId(), null, $tournamentLang['langcode'], ARTICLE_TYPE_NORMAL);
						}

						$data = array(
							'id' => $articleIds['intro'],
							'langcode' => $tournamentLang['langcode'],
							'site_id' => SiteHandler::getCurrentSiteId(),
							'worktitle' => $tournamentLang['nev'] . ' - ' . TextHandler::getText('migr_tournament_article_intro_title', $tournamentLang['langcode']),
							'title' => $tournamentLang['nev'] . ' - ' . TextHandler::getText('migr_tournament_article_intro_title', $tournamentLang['langcode']),
							'body' => $tournamentLang['leiras']
						);
						AdminDBHelper::modArticle($data);
					}

					// eredmeny
					if (! empty($tournamentLang['leiras'])) {
						if (isset($articleIds['result'])) {
							AdminDBHelper::addArticle(SiteHandler::getCurrentSiteId(), $articleIds['result'], $tournamentLang['langcode'], ARTICLE_TYPE_NORMAL);
						} else {
							$articleIds['result'] = AdminDBHelper::addArticle(SiteHandler::getCurrentSiteId(), null, $tournamentLang['langcode'], ARTICLE_TYPE_NORMAL);
						}

						$data = array(
							'id' => $articleIds['result'],
							'langcode' => $tournamentLang['langcode'],
							'site_id' => SiteHandler::getCurrentSiteId(),
							'worktitle' => $tournamentLang['nev'] . ' - ' . TextHandler::getText('migr_tournament_article_results_title', $tournamentLang['langcode']),
							'title' => $tournamentLang['nev'] . ' - ' . TextHandler::getText('migr_tournament_article_results_title', $tournamentLang['langcode']),
							'body' => $tournamentLang['archiv']
						);
						AdminDBHelper::modArticle($data);
					}

				}

				// cikk-verseny kapcsolat mentése
				foreach ($articleIds as $articleId) {
					$data = array(
						'id_tournament' => $tournamentId,
						'id_article' => $articleId
					);
					AdminDBHelper::addTournamentArticle($data);
				}

				// jelentkezések
				$filter = new DBQueryFilter();
				$filter->addComponent('verseny_id', DBQueryFilter::OP_EQUALS, $tournament['id']);
				$registrations =& GeneralDBHelper::getTableRowsFilteredInTransaction($migrDb->get(), 'nevezes', $filter);
				foreach ($registrations as $registration) {
					$data = array(
						'id_tournament' => $tournamentId,
						'id_tournamenttype' => $tournamentTypeIndex[$registration['versenyforma_id']],
					  	'comment' => $registration['megjegyzes'],
						'insdate' => DBUtil::getDBFormattedTimestamp($registration['datum'])
					);
					$registrationId = GeneralDBHelper::addTableRowInTransaction($db->get(), 'registration', $data);

					// nevezők
					$filter = new DBQueryFilter();
					$filter->addComponent('nevezes_id', DBQueryFilter::OP_EQUALS, $registration['id']);
					$registrationPlayers =& GeneralDBHelper::getTableRowsFilteredInTransaction($migrDb->get(), 'nevezo', $filter);
					foreach ($registrationPlayers as $registrationPlayer) {
						$data = array(
							'id_registration' => $registrationId,
						  	'email' => $registrationPlayer['email'],
							'name' => $registrationPlayer['nev']
						);
						GeneralDBHelper::addTableRowInTransaction($db->get(), 'registration_player', $data);
					}
				}
			}
			$db->endTransaction();
		} catch (Exception $e) {
			Log::error("Migrating tournaments failed. Reason: ".$e->getMessage());
			try {
				$db->rollback();
				$db->endTransaction();
			} catch (Exception $e) {
				Log::error("Also, failed to rollback. Reason: ".$e->getMessage());
			}
			throw $e;
		}
	}

}
?>